package com.xiaolong.redis.handle;

import com.xiaolong.common.exception.BusinessException;
import com.xiaolong.redis.annotation.Lock;
import com.xiaolong.redis.exception.SameTaskException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class InterruptHandler implements LockHandler {


    private Logger log = LoggerFactory.getLogger(this.getClass());

    private RedissonClient redissonClient;

    @Override
    public Object execute(ProceedingJoinPoint point, Lock lock) throws Throwable {
        //获取锁的key
        String key = lock.key();
        RLock redisLock = redissonClient.getLock(key);
        Object result = null;
        if (redisLock.isLocked()){
            throw new SameTaskException(lock.msg());
        }
        try {
            redisLock.tryLock(0,lock.waitTime(), TimeUnit.SECONDS);
            result = point.proceed();
        } finally {
            redisLock.unlock();
        }
        return result;
    }
}
